package com.example.train.common.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class AESUtil {

    @Value("${jwt.AESSecret}")
    private String AESSecret;

    @Value("${jwt.AESSalt}")
    private String AESSalt;

    private AES aes;

    //顺序 Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
    @PostConstruct
    public void init(){
        aes = new AES(Mode.CFB, Padding.PKCS5Padding, HexUtil.decodeHex(AESSecret), AESSalt.getBytes());
    }

    public String encrypt(String str){
        Assert.notBlank(str);
        return aes.encryptHex(str);
    }

    public String decrypt(String str){
        Assert.notBlank(str);
        return aes.decryptStr(str);
    }
}
